package com.example.livedata.repository;

import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.example.livedata.api.ApiResponse;
import com.example.livedata.db.dao.UserDao;
import com.example.livedata.entity.UserInfo;
import com.example.livedata.http.NetworkBoundResource;
import com.example.livedata.http.Resource;
import com.example.livedata.service.UserService;


public class UserRepository {

    UserService userService;
    UserDao userDao;

    public LiveData<Resource<UserInfo>> getUser(String userId) {
        return new NetworkBoundResource<UserInfo, UserInfo>() {
            @Override
            public void saveCallResult(@NonNull UserInfo item) {
                userDao.insertAll(item);
            }

            @Override
            public boolean shouldFetch(@Nullable UserInfo data) {
//                return rateLimiter.canFetch(userId) && (data == null || !isFresh(data));
                return data == null;
            }

            @NonNull
            @Override
            public LiveData<UserInfo> loadFromDb() {
                return userDao.getUser(userId);
            }

            @NonNull
            @Override
            public LiveData<ApiResponse<UserInfo>> createCall() {
                return userService.getUser(userId);
            }
        }.getAsLiveData();
    }

}
